package com.watch;

import android.content.Context;
import android.os.Environment;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.utils.SystemUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by daiguangtao on 16/1/25.
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    public static final String TAG = CrashHandler.class.getSimpleName();
    private static CrashHandler INSTANCE = new CrashHandler();
    private Context mContext;
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmm");
    /**
     * 默认存放闪退信息的文件夹名称
     */
    private static final String DEFAULT_CRASH_FOLDER_NAME = "Log";
    /**
     * appSD卡默认目录
     */
    private static final String DEFAULT_APP_FOLDER_NAME = "DefaultCrash";
//    /**
//     * app在SD卡上的主目录
//     */
//    private File mAppMainFolder;
    /**
     * 保存闪退日志的文件目录
     */
    private File mCrashInfoFolder;
    /**
     * 向远程服务器发送错误信息
     */
    private CrashExceptionRemoteReport mCrashExceptionRemoteReport;


    private CrashHandler() {
    }


    public static CrashHandler getInstance() {
        return INSTANCE;
    }

    public void init(Context ctx) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }
    public void init(Context ctx,String crashInfoFolderName) {
        mContext = ctx;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
        if (!TextUtils.isEmpty(crashInfoFolderName)) {
            this.mCrashInfoFolder = new File(crashInfoFolderName);
        }
    }


    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        // if (!handleException(ex) && mDefaultHandler != null) {
        // mDefaultHandler.uncaughtException(thread, ex);
        // } else {
        // android.os.Process.killProcess(android.os.Process.myPid());
        // System.exit(10);
        // }
        if (!handleException(ex) && mDefaultHandler != null) {
            //如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e(TAG, "error : ", e);
            }
            //退出程序
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }

    }


    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. 开发者可以根据自己的情况来自定义异常处理逻辑
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false
     */
    private boolean handleException(Throwable ex) {
//        if (ex == null) {
//            return true;
//        }
        // new Handler(Looper.getMainLooper()).post(new Runnable() {
        // @Override
        // public void run() {
        // new AlertDialog.Builder(mContext).setTitle("提示")
        // .setMessage("程序崩溃了...").setNeutralButton("我知道了", null)
        // .create().show();
        // }
        // });
        System.out.println("handleException");
        if (ex == null) {
            return false;
        }
        saveCrashInfoToFile(ex);
        sendCrashInfoToServer(ex);
        //使用Toast来显示异常信息
        new Thread() {
            @Override
            public void run() {
                Looper.prepare();
                Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }.start();

        return true;
    }

    private void saveCrashInfoToFile(Throwable ex) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
//                if (!mAppMainFolder.exists()) {//app目录不存在则先创建目录
//                    mAppMainFolder.mkdirs();
//                }
                if (!mCrashInfoFolder.exists()) {//闪退日志目录不存在则先创建闪退日志目录
                    mCrashInfoFolder.mkdirs();
                }
                String timeStampString = DATE_FORMAT.format(new Date());//当先的时间格式化
                String crashLogFileName = timeStampString + ".log";
                File crashLogFile = new File(mCrashInfoFolder, crashLogFileName);
                crashLogFile.createNewFile();


                //记录闪退环境的信息
                RandomAccessFile randomAccessFile = new RandomAccessFile(crashLogFile, "rw");
                randomAccessFile.writeChars("------------Crash Environment Info------------" + "\n");
                randomAccessFile.writeChars("------------Manufacture: " + SystemUtils.getDeviceManufacture() + "------------" + "\n");
                randomAccessFile.writeChars("------------DeviceName: " + SystemUtils.getDeviceName() + "------------" + "\n");
                randomAccessFile.writeChars("------------SystemVersion: " + SystemUtils.getSystemVersion() + "------------" + "\n");
                randomAccessFile.writeChars("------------DeviceIMEI: " + SystemUtils.getDeviceIMEI(mContext) + "------------" + "\n");
                randomAccessFile.writeChars("------------AppVersion: " + SystemUtils.getAppVersion(mContext) + "------------" + "\n");
                randomAccessFile.writeChars("------------Crash Environment Info------------" + "\n");
                randomAccessFile.writeChars("\n");
                randomAccessFile.close();


                PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(crashLogFile.getAbsolutePath(), true)), true);
                ex.printStackTrace(pw);//写入奔溃的日志信息
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
    }

    /**
     * 发送发送闪退信息到远程服务器
     *
     * @param ex
     */
    private void sendCrashInfoToServer(Throwable ex) {
        if (mCrashExceptionRemoteReport != null) {
            mCrashExceptionRemoteReport.onCrash(ex);
        }
    }

    /**
     * 闪退日志远程奔溃接口，主要考虑不同app下，把log回传给服务器的方式不一样，所以此处留一个对外开放的接口
     */
    public static interface CrashExceptionRemoteReport {
        /**
         * 当闪退发生时，回调此接口函数
         *
         * @param ex
         */
        public void onCrash(Throwable ex);
    }
}
